/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util.observer;

import util.synch.Atom;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * this timer will run trigger after an amount of time
 * unless tiggered for more time or canceled
 * usefull for maintaining a connection
 * @author martin
 */
public class TimerTrigger implements Runnable, Trigger<Long>{
  //private long _until;
  private final Atom<Long> _until;
  private final Trigger<Long> _callback;
  
  public TimerTrigger(final long until, final Trigger<Long> callback){
    _until=new Atom(until);
    _callback=callback;
  }

  @Override
  public void run() {
    try {
      long tmp = _until.get();
      while(tmp!=0 && !Thread.currentThread().isInterrupted()){
        _until.set(0L);
        Thread.sleep(tmp);
        tmp=_until.get();
      }
    } catch (InterruptedException ex){
      Logger.getLogger(IntervalTrigger.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    if (!Thread.currentThread().isInterrupted())
      _callback.poke(System.nanoTime());
  }

  @Override
  public void poke(Long par0) {
    _until.set(par0);
  }
  
}
